import re
from typing import Callable

from python_part.main_policy_database_member.ReadWriteClass import ReadWriteClass
from python_part.policy_receive.line_solver.line_solver_base import LineSolverBase


class LinkSolver(LineSolverBase):
    def __init__(self,
                 get_all_policy: Callable[[], tuple[dict, dict, dict]],
                 update_entity_path_to_rwclass_id: Callable[[str, int], None],
                 update_rwclass_id_to_rwclass: Callable[[int, ReadWriteClass], None],
                 delete_entity_path_to_rwclass_id: Callable[[str], None],
                 delete_rwclass_id_to_rwclass: Callable[[int], None]):

        super().__init__(get_all_policy, update_entity_path_to_rwclass_id, update_rwclass_id_to_rwclass,
                         delete_entity_path_to_rwclass_id, delete_rwclass_id_to_rwclass)
        self.pattern = re.compile(r"""^link "(.*)", ([1-9]\d*)$""")

    def check_is_this(self, line_content:str) -> bool:
        ans = self.pattern.match(line_content)
        if ans:
            return True
        return False

    def solve_one(self, line_content:str) -> bool:
        match = self.pattern.match(line_content)
        if match:
            file_path = match.group(1)
            read_write_class_id = int(match.group(2))
            self.update_entity_path_to_rwclass_id(file_path, read_write_class_id)
            if self.get_all_policy()[1].get(read_write_class_id) is None:
                tmp = ReadWriteClass()
                tmp.class_id = read_write_class_id
                self.update_rwclass_id_to_rwclass(read_write_class_id, tmp)
            return True
        return False

